#!/usr/bin/env python

__author__ = 'Phong Luu (pluu@google.com)'


import os, sys, logging
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from google.appengine.dist import use_library
use_library('django', '1.2')

import logging
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from google.appengine.api import taskqueue
from google.appengine.api import users
from google.appengine.api import app_identity
from google.appengine.api import memcache
import time
import models
import datetime
import utils
import simplejson
import ytapi_helper
import templatetags.templatefilters
from oauth2client.appengine import CredentialsModel, OAuth2Decorator, \
    StorageByKeyName
import httplib2
from basehandler import BaseUserHandler


ONE_HOUR = 3600


template.register_template_library(
    'django.contrib.humanize.templatetags.humanize')

"""oauth for web apps"""
oauth2_decorator = OAuth2Decorator(
    client_id='607192577077-g0uk89hpko634mm2352663gkmd029f0b.apps.googleusercontent.com',
    client_secret='rRBECXidBhytHlRr3QmaublY',
    scope=" ".join(["http://gdata.youtube.com"]),
    user_agent=app_identity.get_application_id())

class YTCredentialsSetup(webapp.RequestHandler):
  """Setup Oauth2 credentials to be used for an organization.

  Hopefully, this is a onetime setup in order to store the access token
  to be used to upload curated videos into YouTube.
  """
  @oauth2_decorator.oauth_required
  def get(self):
    logging.info(oauth2_decorator)
    owner_id = users.get_current_user().user_id()
    owner_credentials = StorageByKeyName(
        CredentialsModel, owner_id, 'credentials').get()
    
    models.OAuthUser(userid=owner_id).put()
    self.response.out.write(
        'credentials stored, you can close this incognito window now.')



class SingleVideoUpdater(BaseUserHandler):
  """AJAX handler to allow a user to trigger meta refresh for a single video."""
  def __init__(self):
    BaseUserHandler.__init__(self)

  def GetRequest(self):
    videoid = self.request.get('videoid')
    video_data = utils.FetchVideoData(videoid)
    if video_data:
      #update sql db as well
      video_data = video_data[0][0]

      models.Videos().UpdateVideos(video_data)
      self.SendJson(video_data)


class CurateVideoContent(BaseUserHandler):
  """Web handler to manage video curation."""
  def __init__(self):
    BaseUserHandler.__init__(self)
    template.register_template_library('templatetags.templatefilters')
    geo_filter_options = models.Videos.ALL_YT_COUNTRIES
    self.template_values = {
        'geo_filter_options': geo_filter_options,
        'selected_sort_option': 'published',
        'partners_list': self.partners,
        'playlist_list': self.playlists,
        'tagging_checkboxes': self.tags}

  def post(self):
    page_index = int(self.request.get('page_index', '1'))

    partners = self.request.get_all('partners')
    playlists = self.request.get_all('playlists')
    geos = self.request.get_all('geo_filters')
    query_text = self.request.get('search_video', '')
    tags_filter = self.request.get_all('search_tagging', [])
    selected_sort_option = self.request.get('selected_sort_option', 'published')
    logging.info('sort: %s', selected_sort_option)

    if not partners and not playlists:
      playlists = [p.playlist.playlistid for p in self.playlists]
      partners = self.partners

    curator = models.Curator(self.access.organization)
    curator.FilterVideos(
        partners=partners,
        playlists=playlists,
        q=query_text,
        tag_list=tags_filter,
        geo_filters=geos,
        order_by=selected_sort_option,
        page_index=page_index)

    self.SendJson({'total_videos': curator.total_videos,
                   'content': self._InjectHTMLVideoContent(curator.FetchVideos())})


  def _InjectHTMLVideoContent(self, videos):
    return template.render(
        'templates/video_content.html',
        {'tagging_checkboxes': self.tags,'videos': videos})

  def GetRequest(self):
    """Default view handler when user first hits the curation page.

    This method also handles the videoid search feature. All other filters
    are handled in the post handler.
    """
    curator = models.Curator(self.access.organization)
    curator.FilterVideos(partners=self.partners, playlists=None)
    self.template_values.update(
        {'total_videos': curator.total_videos,
         'video_content': self._InjectHTMLVideoContent(curator.FetchVideos())})
    self.Render('all_curator_videos.html', self.template_values)


class AddTagHandler(BaseUserHandler):
  """Handler that adds/removes additional tagging info for a videoid."""
  def __init__(self):
    BaseUserHandler.__init__(self)

  def post(self):
    action = self.request.get('action', 'add')
    videoid = self.request.get('videoid')
    selected_tags = self.request.get_all('tag_names')

    logging.info('%s %s %s', action, videoid, selected_tags)

    if action == 'add':
      curator = models.Curator(self.access.organization)
      try:
        curator.UpdateTags(videoid, selected_tags)
        status_mesg = 'SUCCESS'
        message = 'Additional tags added to videoid: %s' % videoid
      except Exception, e:
        logging.info(e)
        status_mesg = 'FAILED'
        message = str(e)

      message = {'status': status_mesg,
                 'data': selected_tags,
                 'message': message}

    self.SendJson(message)



class UserProfile(BaseUserHandler):
  """User profile handler allowing user to set various prefs."""
  def __init__(self):
    BaseUserHandler.__init__(self)

  def GetRequest(self):
    org_tags = models.Tags.all().filter(
        'organization', self.access.organization).fetch(100)

    template_values = {'tags': org_tags}
    self.Render('manage_user_tags.html', template_values)
  
  def post(self):
    action = self.request.get('action', 'add_tag')
    tag_name = self.request.get('tag_name')
    key_name = '%s_%s' % (self.access.organization.key(), tag_name)
    if action == 'add_tag':
      #cannot add if already in compulsory tagname
      models.Tags.get_or_insert(
          key_name=key_name,
          organization=self.access.organization,
          name=tag_name).put()

    elif action == 'del_tag':
      tag = models.Tags().get_by_key_name(key_name)
      #tags asccoicated to playlists cannot be allowed to be deleted by curator
      if not tag.associate_to_playlist:
        models.db.delete(tag)

    memcache.delete('%s_tags' % self.access.organization.key())
    self.redirect('/profile')


class ReportingHandler(BaseUserHandler):
  REPORT_VIEWS = [
      'Uploaded videos by partner',
      'Curated videos by partner']

  def __init__(self):
    BaseUserHandler.__init__(self)

  def GetRequest(self):
    template_values = {'report_options': self.REPORT_VIEWS}
    self.Render('reporting.html', template_values)

  def _GetReport(self, report_type):
    mem_key = '%s_%s' % (self.access.organization.key(), report_type)
    report_data = memcache.get(mem_key)

    if not report_data:
      reports = models.Reporting(self.access.organization)

      if report_type == 'Uploaded videos by partner':
        report_data = reports.GetPartnerVideoCount()
      elif report_type == 'Curated videos by partner':
        report_data = reports.GetPartnerCuratedVideoCount()

      memcache.set(mem_key, report_data, ONE_HOUR)
    return report_data

  def post(self):
    report_view = self.request.get('report_type', self.REPORT_VIEWS[0])
    template_values = {'reporting_lines': self._GetReport(report_view),
                       'report_options': self.REPORT_VIEWS,
                       'value_description': report_view}
    self.Render('reporting.html', template_values)



class IndexHandler(BaseUserHandler):
  """Redirects / requests to curation handler."""
  def __init__(self):
    BaseUserHandler.__init__(self)
  def GetRequest(self):
    self.redirect('/curate_videos')

def main():
  application = webapp.WSGIApplication([
      ('/', IndexHandler),
      ('/setup_oauth', YTCredentialsSetup),
      ('/update_video', SingleVideoUpdater),

      ('/additional_tags', AddTagHandler),
      ('/profile', UserProfile),
      ('/reporting', ReportingHandler),
      ('/curate_videos', CurateVideoContent)], debug=True)
  util.run_wsgi_app(application)


if __name__ == '__main__':
  main()
